import { AfterViewInit, Component, ElementRef, OnDestroy, ViewChild, ViewEncapsulation } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { Platform } from '@angular/cdk/platform';
import { InitService } from '@core/services/init.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { UserAuthService } from '@core/services/user-auth.service';
import { ReuseTabService } from '@shared/apes/reuse-tab';
import { WebsocketService } from '@core/services/websocket/websocket.service';
import { ActivatedRoute, Router } from '@angular/router';
import { ApesMessageService } from '@shared/apes/message';
import { Promise } from '@ag-grid-community/core';
import { map, mergeMap } from 'rxjs/operators';

@Component({
  selector: 'fnzb-login',
  templateUrl: './fnzb-login.component.html',
  encapsulation: ViewEncapsulation.None,
})
export class FnZbLoginComponent implements AfterViewInit, OnDestroy {

  form: FormGroup;
  error = '';
  type = 0;
  loading: boolean = true;
  count = 0;
  interval$: any;
  _post: any = '';
  postList = [];
  passwordVisible: boolean = false;
  catpcha: boolean = true;
  inputNum: any = 0;
  localStorage: Storage = localStorage;
  @ViewChild('input', { static: false }) input: ElementRef;

  loginPlatform: any;
  terminal: any;

  constructor(private fb: FormBuilder,
              private router: Router,
              private routeInfo: ActivatedRoute,
              public msg: ApesMessageService,
              private initService: InitService,
              private userAuthService: UserAuthService,
              private apiService: ApiService,
              private reuseTabService: ReuseTabService,
              private ws: WebsocketService,
              private platform: Platform) {
    this.initPlatform();
    this.checkPadLogin();

    if (this.type < 1) {
      this.form = fb.group({
        userName: ['', [Validators.required, Validators.minLength(5)]],     // czy01
        password: ['', Validators.required],        // 123456
        post: [''],
        mobile: [''],
        captcha: [''],
        remember: [true],
      });
    }
  }

  fnOneSrc: any;
  fntTheText: any;
  downloadApp: any;
  passwordSrcEye: any;
  passwordSrcEye_invisible: any;

  initPlatform() {
    let data = this.routeInfo.data['value'];
    this.loginPlatform = data['platform'];
    this.terminal = data['terminal'];

    switch (this.loginPlatform) {
      case 'zt' :
        this.fntTheText = '管理后台';
        this.fnOneSrc = './assets/tmp/img/fn/zt-logo.png';
        this.downloadApp = './assets/tmp/img/fn/zt-download.png';
        this.passwordSrcEye = './assets/tmp/img/fn/eye-invisible.png';
        this.passwordSrcEye_invisible = './assets/tmp/img/fn/eye.png';
        break;
      case 'fn' :
        this.fntTheText = '产业互联网赋能平台';
        this.fnOneSrc = './assets/tmp/img/logo/jekun-logo.png';
        this.downloadApp = './assets/tmp/img/fn/download.png';
        this.passwordSrcEye = './assets/tmp/img/fn/eye-invisible-black.png';
        this.passwordSrcEye_invisible = './assets/tmp/img/fn/eye-black.png';
        break;
      case 'gys' :
        this.fntTheText = '供应商平台';
        this.fnOneSrc = './assets/tmp/img/logo/jekun-logo.png';
        this.downloadApp = './assets/tmp/img/fn/download.png';
        this.passwordSrcEye = './assets/tmp/img/fn/eye-invisible-black.png';
        this.passwordSrcEye_invisible = './assets/tmp/img/fn/eye-black.png';
        break;
      default :
        this.fntTheText = '管理后台';
        this.fnOneSrc = './assets/tmp/img/fn/zt-logo.png';
        this.downloadApp = './assets/tmp/img/fn/zt-download.png';
        this.passwordSrcEye = './assets/tmp/img/fn/eye-invisible.png';
        this.passwordSrcEye_invisible = './assets/tmp/img/fn/eye.png';
    }
  }

  ngAfterViewInit() {
    setTimeout(() => {
      this.input.nativeElement.focus();
    }, 1000);
  }

  /**
   * 功能：判断是否记住密码，如果记住密码就直接跳过登录
   */
  checkPadLogin() {
    if (this.platform.ANDROID) {
      const userInfo = this.userAuthService.getUserInfoObj();
      if (userInfo && userInfo.userAccount) {
        const user = userInfo.userAccount;
        const hash = this.userAuthService.getUserHash(user.userId);
        if (this.type < 1) {
          const userModel = { userId: user.userId, password: user.password, post: user.post, terminal: this.terminal, hash: hash };
          if (userModel.userId) {
            this.mergeLoginData(userModel, 'aut.user.login', 'userId');
          } else {
            this.msg.error('用户信息缺失，请退出重新登录！'); // 该用户已禁用，请联系行政人员
          }
        } else {
          const userModelApp = { phone: user.phone, captcha: user.captcha, post: user.post, terminal: this.terminal, hash: hash};
          this.mergeLoginData(userModelApp, 'aut.user.loginApp', 'phone');
        }
      }
    }
  }

  get userName() {
    return this.form.controls.userName;
  }

  get password() {
    return this.form.controls.password;
  }

  get mobile() {
    return this.form.controls.mobile;
  }

  get post() {
    return this.form.controls.post;
  }

  get captcha() {
    return this.form.controls.captcha;
  }

  switch(ret: any) {
    this.type = ret.index;
    this.error = '';
    if (this.type >= 1) {
      this.form = this.fb.group({
        userName: [''],     // czy01
        password: [''],        // 123456
        post: [''],
        mobile: ['', [Validators.required, Validators.pattern(/^1\d{10}$/)]],
        captcha: ['', [Validators.required]],
        remember: [true],
      });
    } else {
      this.form = this.fb.group({
        userName: ['', [Validators.required, Validators.minLength(5)]],     // czy01
        password: ['', Validators.required],        // 123456
        post: [''],
        mobile: [''],
        captcha: [''],
        remember: [true],
      });
    }

  }

  // 获取验证码
  getCaptcha() {
    this.count = 59;
    if (!this.mobile.value) {
      return;
    }
    const userModel = { phone: this.mobile.value };
    this.apiService.post('aut.user.getCaptchaApp', { 'body': JSON.stringify(userModel) }).subscribe(
      (body) => {
        if (body) {
          // console.log(body);
        } else {
          this.error = '验证码发送不正确';
        }
      });
    this.interval$ = setInterval(() => {
      this.count -= 1;
      if (this.count <= 0)
        clearInterval(this.interval$);
    }, 1000);
  }

  select(param) {
    this._post = '';
    let index = param.selectedIndex - 1;
    this._post = this.postList[index];
  }

  check() {
    this.userName.markAsDirty();
    this.password.markAsDirty();
    this.mobile.markAsDirty();
    this.captcha.markAsDirty();
    let result = true;
    if (this.type < 1) {
      if (!this.userName.value) {
        this.error = '账号或密码不正确';
        result = false;
        return result;
      }
      if (!this.password.value) {
        this.error = '账号或密码不正确';
        result = false;
        return result;
      }
    } else {
      if (!this.mobile.value) {
        this.error = '手机号或验证码不正确';
        result = false;
        return result;
      }
      if (!this.captcha.value) {
        if (this.count > 0) {
          this.error = '';
        } else {
          this.error = '手机号或验证码不正确';
        }
        result = false;
        return result;
      }
    }

    return result;
  }

  login(): void {
    this.error = '';
    if (!this.check()) {
      return;
    }

    const hash = this.userAuthService.getUserHash(this.userName.value);
    if (this.type < 1) {
      const userModel = {
        userId: this.userName.value,
        password: this.password.value,
        post: this._post,
        terminal: this.terminal,
        hash: hash
      };
      if (userModel.userId) {
        this.mergeLoginData(userModel, 'aut.user.login', 'userId');
      } else {
        this.msg.error('用户信息缺失，请退出重新登录！'); // 该用户已禁用，请联系行政人员
      }
    } else {
      const userModelApp = {
        phone: this.mobile.value,
        captcha: this.captcha.value,
        post: this._post,
        terminal: this.terminal,
        hash: hash
      };
      this.mergeLoginData(userModelApp, 'aut.user.loginApp', 'phone');
    }


  }

  // mergeMap登录
  mergeLoginData(userModel: any, api: string, name: string) {
    return new Promise(resolve => {
      this.userGetPost(userModel).pipe(
        map(body => {
          return body;
        }),
        mergeMap((data) => this.userLogin(data, api)),
      ).subscribe(body => {
        resolve(body);
        if (body) {
          const resultData = body.user;
          let post = this.userAuthService.getPost(resultData[name]) ? this.userAuthService.getPost(resultData[name]) : userModel.post;
          for (const item of resultData['posts']) {
            if (item === post) {
              break;
            }
          }

          resultData['post'] = post;
          resultData[name] = userModel[name];
          if(!resultData.hasOwnProperty('userId')){
            resultData['userId'] = body.user['origin'];
          }
          resultData['terminal'] = this.terminal;

          // console.log(this.routeInfo);

          const userInfo = {
            'token': body.sessionId,
            'userAccount': resultData,
            'terminal': this.terminal,
            'platform': this.loginPlatform,
          };

          this.userAuthService.storeUserInfo(JSON.stringify(userInfo));
          this.userAuthService.storeUserInfoLocal(JSON.stringify(userInfo));
          this.userAuthService.storUserPostLocal(resultData[name], JSON.stringify(post));
          // APP登录失效 判断localStorage是否有backPage
          let backPage = this.localStorage.getItem('backPage');
          if (backPage) {
            window.open(backPage, '_self');
          } else {
            this.router.navigate(['']);
          }

          // 登录后清除backPage
          this.localStorage.removeItem('backPage');

          // 清除复用路由导航
          this.reuseTabService.clear();
          this.ws.connect(userInfo.userAccount.id);
        } else {
          if (this.type < 1) {
            this.error = '账号或密码不正确';
          } else {
            this.error = '手机号或验证码不正确';
          }
        }
      });
    });
  }

  // 用户账号获取岗位
  userGetPost(userModel: any) {
    this.error = '';
    if (this.type < 1) {
      this.catpcha = true;
      if (!this.userName.value) {
        return;
      }
      const data = { userId: userModel.userId };
      return this.apiService.post('aut.user.getPosts', { 'body': JSON.stringify(data) })
        .pipe(map(body => {
          if (body) {
            if (body.length > 0) {
              const post = this.userAuthService.getPost(userModel.userId) ? this.userAuthService.getPost(userModel.userId) : body[0];
              this.postList = body.filter((item) => item.id === post.id);
              const posts = this.postList[0] ? this.postList[0] : body[0];
              this.form.patchValue({ post: posts });
              this._post = posts;
              userModel.post = this._post;
              return userModel;
            } else {
              this.error = '请给操作员分配角色！';
              return;
            }
          } else {
            this.error = '账号不正确，请检查！';
          }
        }));
    } else {
      if (!this.mobile.value) {
        return;
      }
      const data = { phone: userModel.phone };
      return this.apiService.post('aut.user.getPostToApp', { 'body': JSON.stringify(data) })
        .pipe(map(body => {
          if (body) {
            const post = this.userAuthService.getPost(userModel.phone) ? this.userAuthService.getPost(userModel.phone) : body[0];
            this.postList = body.filter((item) => item.id === post.id);
            const posts = this.postList[0] ? this.postList[0] : body[0];
            this.form.patchValue({ post: posts });
            this._post = posts;
            userModel.post = this._post;
            this.catpcha = false;
            return userModel;
          } else {
            this.error = '手机号不正确，请检查';
            this.catpcha = true;
          }
        }));
    }
  }

  // 用户登录
  userLogin(userModel: any, api: string) {
    this.initService.loadI18n();
    if (!userModel) return;
    return this.apiService.post(api, { 'body': JSON.stringify(userModel) })
      .pipe(
        map(body => {
          return body;
        }),
      );
  }

  inputCaptcha(e) {
    this.inputNum = e;
  }

  mobileChanges(e) {
    if (e.length === 11) {
      this.catpcha = false;
    } else {
      this.catpcha = true;
    }
  }

  openDownloadApp() {
    let link = '/upload/app/index';
    window.open('/app' + link, '_self');
  }

  ngOnDestroy(): void {
    if (this.interval$) {
      clearInterval(this.interval$);
    }
  }
}
